<?php

namespace App\Services\Pay;

use App\Constants\CodeData;
use App\Constants\PayCodeData;
use App\Dao\CommonSettingDao;
use App\Dao\OrderDao;
use App\Exception\MessageException;
use App\Model\ConfigPayPlatform;
use App\Model\Forbidden;
use App\Model\Order;
use App\Services\PayPlus\IndoPlusPayment;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use Hyperf\DbConnection\Db;
use function Hyperf\Config\config;

class PaySevice
{

    /**
     * Note - 获取支付列表
     * DateTime 2024/8/23 14:25
     * User Admin
     * @param $userInfo
     * @param $params
     * @return array
     */
    public function payProductList($userInfo, $params)
    {
        // os_type		1:android	2:iOS
        // trade_type	1:alipay	2:wxpay     3:ApplePay    10:googlePay     11:payPlus
        // channel_type	1:cpa		2:cps
        // safe_type	1:safe_user	2:new_user
        // buy_type		1:gold		2:vip

        $uid = $userInfo['id'];
        $version_code = (int)$params['version_code'];
        $os_type = intval($params['from'] ?? 1); // 1:android, 2:iOS
        $channel = (string)$params['channel'];
        $package = (string)$params['package'];
        $language = (string)$params['language'];

        $switch_from = intval($params['switch_from'] ?? 0); // 0:gold, 1:vip 2:快捷支付
        if ($switch_from == 0) {
            $buy_type = 1;    // 金币充值
        } else {
            $buy_type = 2;    // vip充值 当 switch_from=2 时,购买的是聊币, 但是使用的是vip的通道
        }

        $local_code = intval($params['local_code'] ?? 1);    // 0:大陆, 1:海外

        $channel_type = $userInfo['register_call_force_vip'] == 1 ? 2 : 1;
        $record = Order::query()->where([
            ['pay_status', '=', 1],
            ['notify_status', '=', 1],
            ['uid', '=', $uid],
            ['price', '>', 10],
        ])->selectRaw('count(id) as count, min(pay_time) as first_time')->first();
        $record = modelToArray($record);
        $safe_type = 2;
        if ($record && $record['count'] >= 2 && $record['first_time'] < time() - 86400 * 2) {
            $safe_type = 1;
        }

        $records = ConfigPayPlatform::query()
            ->where('valid', 1)->where('weight', '>', 0)->where('version_min', '<=', $version_code)
            ->where(function ($query) use ($os_type) {
                $query->where('os_type', $os_type)->orWhere('os_type', 0);
            })->where(function ($query) use ($safe_type) {
                $query->where('safe_type', $safe_type)->orWhere('safe_type', 0);
            })
            ->where(function ($query) use ($channel_type) {
                $query->where('channel_type', $channel_type)->orWhere('channel_type', 0);
            })->where(function ($query) use ($buy_type) {
                $query->where('buy_type', $buy_type)->orWhere('buy_type', 0);
            })->where(function ($query) use ($package) {
                $query->where('package', 'like', '%' . $package . '%')->orWhere('package', '')->orWhere('os_type', 2);
            })
            ->orderBy('weight', 'desc')
            ->get()->toArray();

        $switch_payPlus = false;
        $switch_ios_pay = false;
        $switch_google_pay = false;

        foreach ($records as $record) {
            if ($record['trade_type'] == PayCodeData::IOS_PAY) $switch_ios_pay = true;
            if ($record['trade_type'] == PayCodeData::GOOGLE_PAY) $switch_google_pay = true;
            if ($record['trade_type'] == PayCodeData::PAY_PLUS_INDO) $switch_payPlus = true;
        }


        // 今日充值总金额
        $today_recharge_num = Order::query()->where([
            ['pay_status', '=', 1],
            ['uid', '=', $uid],
        ])->where('pay_time', '>=', strtotime(date('Y-m-d')))->sum('price');
        $is_exceed = 0;
        $limit = CommonSettingDao::getValue("today_recharge_limit");
        if ($today_recharge_num >= $limit) {
            $is_exceed = 1;
        }

        $agreement = HOST . "/app/h5/huanyu/recharge_xieyi.html";
        if ($package == 'com.tongcheng.mojiaoyou') {
            $agreement = HOST . "/app/h5/hualiao/recharge_xieyi.html";
        } elseif ($package == 'com.xun.liao') {
            $agreement = HOST . "/app/h5/xunliao/recharge_xieyi.html";
        }

        $pay_menu = [];
        //海外
        if ($local_code > 0) {
            $quick_recharge = [];
            if ($os_type == 1) {
                $payData = config('pay_data_google');
                //android
                if ($switch_from == 1) {  // 0:gold, 1:vip 2:快捷支付
                    $pay_menu[] = array('show' => 1, 'desc' => 'GooglePay', 'pay_type' => 10, "gold_prices" => $payData[$language]['google_gold'], "vip_prices" => $payData[$language]['google_vip']);
                } else {
                    $pay_menu[] = array('show' => 1, 'desc' => 'GooglePay', 'pay_type' => 10, "gold_prices" => $payData[$language]['google_gold']);
                }
                // 是否首次充值
                $res = OrderDao::getInstance()->checkFirstRecharge($uid);
                if ($res) {
                    // 没有首充
                    $gold_prices = array_values($payData[$language]['google_gold']);
                    $quick_recharge = array_slice($gold_prices, 0, 4);
                }
            } else {
                $payData = config('pay_data_ios');
                //iOS
                if ($switch_from == 1) {    // vip
                    $pay_menu[] = array('show' => 1, 'desc' => 'ApplePay', 'pay_type' => 3, "gold_prices" => $payData[$language]['ios_gold'], "vip_prices" => $payData[$language]['ios_vip']);
                } else {
                    $pay_menu[] = array('show' => 1, 'desc' => 'ApplePay', 'pay_type' => 3, "gold_prices" => $payData[$language]['ios_gold']);
                }
            }
            if ($switch_payPlus) {
                $payData = config('pay_data_payPlus_indo');
                if ($switch_from == 1) {    // vip
                    $pay_menu[] = array('show' => 1, 'desc' => 'payPlus_indo', 'pay_type' => 11, "gold_prices" => $payData[$language]['payPlus_gold'], "vip_prices" => $payData[$language]['payPlus_vip']);
                } else {
                    $pay_menu[] = array('show' => 1, 'desc' => 'payPlus_indo', 'pay_type' => 11, "gold_prices" => $payData[$language]['payPlus_gold']);
                }
            }

            // Tool::JSON(\CodeData::SUCCESS, array(
            //         'agreement' => $agreement,
            //         'is_exceed' => $is_exceed,
            //         'pay_switch' => 1,
            //         'first_recharge' => $quick_recharge,
            //         'quick_recharge' => $quick_recharge,
            //         'pay_menu' => $pay_menu)
            // );
            return formatData([
                'agreement' => $agreement,
                'is_exceed' => $is_exceed,
                'pay_switch' => 1,
                'first_recharge' => $quick_recharge,
                'quick_recharge' => $quick_recharge,
                'pay_menu' => $pay_menu
            ]);
        }
        return formatData([]);
    }

    /**
     * Note - 创建支付订单
     * DateTime 2024/8/23 15:40
     * User Admin
     * @param mixed $userInfo
     * @param mixed $params
     * @return array
     */
    public function createPayOrder(mixed $userInfo, mixed $params)
    {
        $uid = $userInfo['id'];
        $language = $params['language'];
        // $openId = $params['openId'] ?? "";
        $os_type = isset($params['from']) ? intval($params['from']) : 1;// 平台类型 1:android   2:iOS
        $package = $params['package'] ?? "";
        // $money = isset($params['money']) ? intval($params['money']) : 0;
        $version_code = isset($params['version_code']) ? intval($params['version_code']) : 0;
        $pay_from = $params['pay_from'] ?? '';
        $user_id = isset($params['order_robot_id']) ? intval($params['order_robot_id']) : 0;  // 被访问用户id(购买微信、视频等必须)
        $goods_id = isset($params['goods_id']) ? intval($params['goods_id']) : 0;  // 购买的视频或图片id
        $order_from_type = isset($params['order_from_type']) ? intval($params['order_from_type']) : 0;  //订单来源标识
        $consume_type = intval($params['consume_type']);
        $trade_type = intval($params['pay_type']);

        $productId = $params['product_id'] ?? ''; // 购买商品id，针对第三方支付
        if (!$productId && $trade_type == PayCodeData::PAY_PLUS_INDO) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', "参数错误");
            throw new MessageException("参数错误");
        }


        //  检查按城市过滤
        $ip = FunUtil::getClientIp();
        $_ip = sprintf("%u", ip2long($ip));
        if ($userInfo['inviteUid'] == 0 && !(new Forbidden())->check($userInfo["city"], $userInfo["province"], 2)) {
            throw new MessageException("参数错误[1]");
        }


        if ($consume_type == 30) {
            // 测试支付充值
            $buy_item = [
                'title' => "1金币",
                'goods_count' => '1',
                'price' => '1',
                'discount_price' => '0.1',
                'from_price' => '￥1',
                'consume_type' => 30,
                'tag_value' => '特惠',
                'send_good' => '0',
                'sub_title' => '',
                'display' => 0,     //0显示，1隐藏
                'default_select' => 1,//默认选中
            ];
        } else {
            $items = [];
            if ($trade_type == PayCodeData::GOOGLE_PAY) {
                $infoConfig = config('pay_data_google');
                if ($consume_type < 50) {
                    // consume_type<50：充值金币
                    $items = $infoConfig[$language]['google_gold'];
                } else if ($consume_type < 60) {
                    // consume_type>=50 且 consume_type<60：充值VIP
                    $items = $infoConfig[$language]['google_vip'];
                } else {
                    // consume_type>=60：充值SVIP
                    $items = $infoConfig[$language]['google_super_vip'];
                }
            }
            if ($trade_type == PayCodeData::IOS_PAY) {
                $infoConfig = config('pay_data_ios');
                if ($consume_type < 50) {
                    // consume_type<50：充值金币
                    $items = $infoConfig[$language]['ios_gold'];
                } else if ($consume_type < 60) {
                    // consume_type>=50 且 consume_type<60：充值VIP
                    $items = $infoConfig[$language]['ios_vip'];
                } else {
                    // consume_type>=60：充值SVIP
                    $items = $infoConfig[$language]['ios_super_vip'];
                }
            }
            if ($trade_type == PayCodeData::PAY_PLUS_INDO) {
                $infoConfig = config('pay_data_payPlus_indo');
                if ($consume_type < 50) {
                    // consume_type<50：充值金币
                    $items = $infoConfig[$language]['payPlus_gold'];
                } else if ($consume_type < 60) {
                    // consume_type>=50 且 consume_type<60：充值VIP
                    $items = $infoConfig[$language]['payPlus_vip'];
                } else {
                    // consume_type>=60：充值SVIP
                    $items = $infoConfig[$language]['payPlus_super_vip'];
                }
            }

            foreach ($items as $item) {
                if ($item['consume_type'] == $consume_type) {
                    $buy_item = $item;
                }
            }
        }

        if (!isset($buy_item)) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', "buy_item is null");
            throw new MessageException("buy_item is null", CodeData::NEED_TIPS, [], false);
        }
        LoggerUtil::write("pay", $buy_item, "buy_item");

        $money = floatval($buy_item["discount_price"]);
        $date = date("Y-m-d");


        // 获取支付通道
        $configPayPlatformModel = new ConfigPayPlatform();
        list($platform, $pay_type, $pay_platform_id) = $configPayPlatformModel->getPayPlatform($os_type, $trade_type, $package, $version_code, $money, $pay_from);
        if (empty($pay_platform_id)) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', "支付通道不存在");
            throw new MessageException("支付通道不存在");
        }

        try {
            Db::beginTransaction();
            //插入订单表
            $orderId = FunUtil::formatUniqidOrderId(5); //获取唯一订单号
            $data = array(
                'order_id' => $orderId,
                'uid' => $uid,
                'pay_platform_id' => $pay_platform_id,
                'type' => $pay_type,
                'consume_type' => $consume_type,
                'channel' => $userInfo['channel'],
                'fee' => round($money, 2), //金额
                'price' => round($money, 2), //价格
                'goods' => $buy_item['goods_count'], //数量,
                'description' => $buy_item['title'],
                'send_good' => isset($buy_item['send_good']) ? intval($buy_item['send_good']) : 0, //充值送金币
                'pay_status' => 2,
                'notify_status' => 0, //同步状态 0，未同步
                'pay_time' => time(),
                'oaid' => $userInfo['oaid'],
                'imei' => $userInfo['imei'],
                'imsi' => "",
                'ip' => FunUtil::getClientIp(),
                'package' => $package,
                'from' => $os_type,
                'version_code' => $version_code,
                'order_from_type' => $order_from_type, //支付来源
                'order_robot_id' => isset($params['order_robot_id']) ? (int)$params['order_robot_id'] : 0, //产生订单时的来源主播id
                'trade_type' => $trade_type,
                'auto_xiubi' => 0,//去除秀币
                'send_chat_coin' => 0, //去除聊币
                'user_id' => $user_id, // 购买的微信号用户id
                'goods_id' => $goods_id ?: 0, // 购买视频或图片id
            );
            LoggerUtil::write("pay", $data, "insert_tb_order");
            $result = Order::query()->insert($data);
            if (!$result) {
                throw new MessageException("插入订单表失败");
            }


            $url = '';
            $url_params = '';
            $path = '';
            $pay_params = array("platform" => $platform);
            $data['productId'] = $buy_item['product_id'] ?? 'test';
            $data['productType'] = $buy_item['product_type'] ?? 'inapp';

            if ($pay_type == PayCodeData::PAY_PLUS_INDO) { // payPlus支付 印尼

                $data['phone'] = $userInfo['phone'] ?: $userInfo['id'];
                $data['name'] = $userInfo['nickname'];
                $data['email'] = $data['phone'] . '@gmail.com';
                $params = (new IndoPlusPayment($pay_platform_id))->createPayOrder($data);
                $url = $params['payUrl'];
                $sdk_type = 'payPlus_indod';
                Order::query()->where('order_id', $orderId)->update(['trade_id' => $params['platOrder']]);
            }

            if ($pay_type == PayCodeData::GOOGLE_PAY) {
                $sdk_type = 'googlePay';
            }

            if ($pay_type == PayCodeData::IOS_PAY) {
                $sdk_type = 'iosPay';
            }
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            LoggerUtil::write('create_pay_order', $e->getMessage());
            throw new MessageException('创建订单失败');
        }

        $result = array(
            'url' => $url,
            'url_params' => $url_params,
            'referer' => $referer ?? "",
            'path' => $path,
            'sdk_type' => $sdk_type ?? $platform,
            'platform' => $platform,
            'pay_params' => $pay_params,
            'order_info' => $data,
        );

        LoggerUtil::write("pay", $result, "result");

        // Tool::JSON(\CodeData::SUCCESS, $result);
        return formatData($result);

    }

}